<?php
/**
 * File to handle all API requests
 * Accepts GET and POST
 *
 * Each request will be identified by TAG
 * Response will be JSON data
 
  /**
 * check for POST request
 */
if (isset($_POST['tag']) && $_POST['tag'] !== '') {
    // get tag
    $tag = $_POST['tag'];
     
	require_once('../function/includes.php');
	
    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);
 
    // check for tag type
    if ($tag === 'login') {
        // Request type is check Login
        $username = $_POST['username'];
        $user_password = $_POST['password'];
 
		$login = User::compare($username, $user_password);
		$user_id = User::findID($username);
		
		//Check if log in
		if ($login === 0) {

			// user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
			
		} else {
			
			// get user info
			$user = User::createUser($user_id);
			
			//create session			
			$sessionLog = new Session($user_id);
			$sessionLog->remember();
			
			// user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user_id;
            $response["user"]["name"] = $user->getUsername();
            $response["user"]["email"] = $user->getEmail();
			$response["user"]["role"] = $user->getRole();
			$response["user"]["session"] = $sessionLog->getToken();
            $response["user"]["created_at"] = $user->getTime();
            //$response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
		
		}

    } else if ($tag === 'register') {
        // Request type is Register new user
		$username = $_POST['username'];
        $email = $_POST['email'];
        $password = $_POST['password'];
		$firstName = $_POST['firstName'];
		$lastName = $_POST['lastName'];
		
		$address1 = $_POST['address1'];
		$address2 = $_POST['address2'];
		$city = $_POST['city'];
		$state = $_POST['state'];
		$country = $_POST['country'];
		$postcode = $_POST['postcode'];	

		$address = $address1."|".$address2."|".$city."|".$state."|".$country."|".$postcode;
		
		$bloodtype = $_POST['bloodtype'];	
		$allergies = $_POST['allergies'];	
		$patient_benchmark = $_POST['benchmark'];
		
		$contact = $_POST['contact'];
		$dob = $_POST['dob'];
		$gender = $_POST['gender'];

        // check if user is already existed
        if (User::checkUsername($username)) {
            // user is already existed - error response
            $response["success"] = 2;
			
			echo json_encode($response);
        } else if (User::checkEmail($email)) {
            // user is already existed - error response
            $response["success"] = 3;
			
			echo json_encode($response);
        } else {
			
			// Register patient - app doesn't create Doctors or Admin.
			$user = new Patient($username, $password, $email, $firstName, $lastName, 
									$gender, $address, $contact, $dob, "patient", null,
									$bloodtype, $allergies, $patient_benchmark);
			$user->insert();
			
			//create session			
			$sessionLog = new Session($user->getUserID());
			$sessionLog->remember();

            if ($user !== 0) {
                // user stored successfully
                $response["success"] = 1;
				$response["user"]["uid"] = $user->getUserID();
				$response["user"]["session"] = $sessionLog->getToken();
				$response["user"]["role"] = $user->getRole();

                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else if ($tag === "check_tag"){
		// Request type is Register new user
        $user_id = intval($_POST['userID']);
        $sessionToken = $_POST['sessionToken'];
		
		// get id associated with the token, if any.
		$sessionID = Session::findID($sessionToken);
		
		//Check to see if the user id associated with the token is the same as ours. 
		if ($user_id === $sessionID && $sessionToken !== "") {
		
			$user = User::createUser($sessionID);
			
			// session found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user->getUserID();
			$response["user"]["role"] = $user->getRole();

            echo json_encode($response);			
		} else {
			// user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Session not active!";
            echo json_encode($response);		
		}
	
	} else if ($tag === "delete_session_tag"){ 
		// Request type is Register new user
        $user_id = intval($_POST['userID']);
        $sessionToken = $_POST['sessionToken'];
		$android_id = $_POST['androidID'];
		
		//create session			
		$sessionRemove = new Session($user_id);
		// remove android ID from receiving notifications
		$androidRemove = false;
		if($android_id !== ""){
			$androidRemove = User::removeAndroidID($user_id, $android_id);
		}
		if($sessionRemove->remove($user_id, $sessionToken) && $androidRemove){
			// session found and removed
            // echo json with success = 1
            $response["success"] = 1;
            echo json_encode($response);
		} else {
			// user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Failed to delete session.";
            echo json_encode($response);	
		}
	} else if($tag === "get_connection_list"){

		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		if($session === $user_id){
			
			$connection_list = null;

			if(User::findRole($user_id) === "doctor"){
				$user = Doctor::createUser($user_id);
				
				// get the raw patient list (has only id)
				$raw_connection_list = $user->getPatientList();
				// set the name to retieve from the connection list.
				$typeID = "patient_id";
				
				// Convert from PHP class object to strings ----> i think.
				for($i = 0; $i < sizeof($raw_connection_list); $i++){		
					/* use the connections typeID to retrieve their name
					* $raw_connection_list[$i][$typeID] -> retreieves the ID for the user.
					*/
					$tempUserId = $raw_connection_list[$i][$typeID];
					
					$connection_list[$i]["connection_name"] = User::findName($tempUserId);				
					$connection_list[$i]["connection_id"] = $tempUserId;	
					$patientUser = Patient::createUser($tempUserId);
					$connection_list[$i]["contact"] = $patientUser->getContact();
					$connection_list[$i]["gender"] = $patientUser->getGender();
					$connection_list[$i]["email"] = $patientUser->getEmail();
					$connection_list[$i]["dob"] = $patientUser->getDoB();
					$connection_list[$i]["blood_type"] = $patientUser->getBloodtype();
					$connection_list[$i]["allergy"] = $patientUser->getAllergy();

					if($raw_connection_list[$i]["request_pending"] == 0){
						$connection_list[$i]["pending"] = "accepted";
					} else {
						$connection_list[$i]["pending"] = "Waiting";
					}
				}					
			} else {
				$user = Patient::createUser($user_id);
				// get the raw patient list (has only id)
				$raw_connection_list = $user->getDoctorList();
				// set the name to retieve from the connection list.
				$typeID = "doctor_id";			
				
				// Convert from PHP class object to strings ----> i think.
				for($i = 0; $i < sizeof($raw_connection_list); $i++){		
					/* use the connections typeID to retrieve their name
					* $raw_connection_list[$i][$typeID] -> retreieves the ID for the user.
					*/
					$tempUserId = $raw_connection_list[$i][$typeID];
					
					$connection_list[$i]["connection_name"] = User::findName($tempUserId);				
					$connection_list[$i]["connection_id"] = $tempUserId;	
					$drUser = Doctor::createUser($tempUserId);
					$connection_list[$i]["contact"] = $drUser->getContact();
					$connection_list[$i]["gender"] = $drUser->getGender();
					$connection_list[$i]["email"] = $drUser->getEmail();
					$connection_list[$i]["regno"] = $drUser->getRegno();
					$connection_list[$i]["hospital"] = $drUser->getHospitalList();
					$connection_list[$i]["speciality"] = $drUser->getSpeciality();

					if($raw_connection_list[$i]["request_pending"] == 0){
						$connection_list[$i]["pending"] = "accepted";
					} else {
						$connection_list[$i]["pending"] = "Waiting";
					}
				}			
			}									
			if($connection_list !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				$response["connectionList"] = $connection_list;

				echo json_encode($response);
			} else {
				// list is emptty, no connections.
				$response["success"] = 2;			
				echo json_encode($response);	
			}
		}	
	} else if($tag === "search_doctors_list"){

		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];	
		$search = $_POST['search'];
		
		$session = Session::findID($token);
		
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		if($session === $user_id){
			$doctorsList = null;
			if(User::findRole($user_id) === "doctor"){
				$doctorsList = Doctor::searchDoctor($search);
			} else {
				$user = Patient::createUser($user_id);
				// get list of all registered doctors
				$doctorsList = Doctor::searchDoctor($search);
				// get list of doctors that the patient is connected to.
				$pendingDoctors = $user->getDoctorList();
				// go through each registered doctor.
				if($doctorsList!= null){
					foreach ($doctorsList as &$doctor) {
						// go through each doctor registerd with user.
						foreach ($pendingDoctors as $pending) {
							// if they both match, then that doctor is registered and needs to be tagged.
							if($pending['doctor_id'] === $doctor['user_id']){
								// check the connection status and tag with the appropriate tag.							
								if($user->checkDoctor($doctor["user_id"], $user_id)){
									$doctor["pending"] = "accepted";
								} else {
									$doctor["pending"] = "waiting";
								}
							}
						}
					}
				}
			}
			
			if($doctorsList !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				$response["doctors_list"] = $doctorsList;

				echo json_encode($response);
			} else {
				// list is emptty, no connections.
				$response["success"] = 2;			
				echo json_encode($response);	
			}
		}
		
	} else if($tag === "get_doctors_list"){

		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		if($session === $user_id){
			$doctorsList = null;
			if(User::findRole($user_id) === "doctor"){
				$doctorsList = Doctor::searchDoctor();
			} else {
				$user = Patient::createUser($user_id);
				// get list of all registered doctors
				$doctorsList = Doctor::searchDoctor();
				// get list of doctors that the patient is connected to.
				$pendingDoctors = $user->getDoctorList();
				// go through each registered doctor.
				
				if($doctorsList !== null && $pendingDoctors !== null){
					foreach ($doctorsList as &$doctor) {
						// go through each doctor registerd with user.
						foreach ($pendingDoctors as $pending) {
							// if they both match, then that doctor is registered and needs to be tagged.
							if($pending['doctor_id'] === $doctor['user_id']){
								// check the connection status and tag with the appropriate tag.							
								if($user->checkDoctor($doctor["user_id"], $user_id)){
									$doctor["pending"] = "accepted";
								} else {
									$doctor["pending"] = "waiting";
								}
							}
						}
					}
				}
			}
			
			if($doctorsList !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				$response["doctors_list"] = $doctorsList;

				echo json_encode($response);
			} else {
				// list is emptty, no connections.
				$response["success"] = 2;			
				echo json_encode($response);	
			}
		}
		
	} else if($tag === "remove_patient_request"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$patient = $_POST['patient'];		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.		
		if($session === $user_id){	
			if(User::findRole($user_id) === "doctor"){
				// Create Doctor user
				$user = Doctor::createUser($user_id);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
			// remove the patient from the doctors list.
			$user->removeRequestFrom($patient);
			// check if the patient has been removed successfully.
			$fail = $user->isPatient($patient);
			//check to see if removing patient failed.
			if($fail === false){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to remove patient";
				echo json_encode($response);	
			}
		}

	} else if($tag === "accept_patient_request"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$patient = $_POST['patient'];	
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.	
		if($session === $user_id){
			$user = Doctor::createUser($user_id);
			// accept the patient from the doctors list.
			$success = $user->acceptRequest($patient);
			//check to see if removing patient failed.
			if($success === true){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to remove patient";
				echo json_encode($response);	
			}
		}

	} else if($tag === "remove_doctor"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$doctor = $_POST['doctor'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		
		if($session === $user_id){
			$user = Patient::createUser($user_id);
			// accept the patient from the doctors list.
			$success = $user->removeRequestFrom($doctor);

			//check to see if removing patient failed.
			if($success === true){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to remove doctor";
				echo json_encode($response);	
			}
		}

	} else if($tag === "add_doctor"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$doctor = $_POST['doctor'];
		$note = $_POST['note'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		
		if($session === $user_id){
			$user = Patient::createUser($user_id);
			// accept the patient from the doctors list.
			$success = $user->sendRequestTo($doctor, $note);

			//check to see if removing patient failed.
			if($success === true){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;			
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to add doctor";
				echo json_encode($response);	
			}
		}

	} else if($tag === "get_profile"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		
		if($session === $user_id){
			// check the role of the user.
			if(User::findRole($user_id) === "doctor"){
				// Create Doctor user
				$user = Doctor::createUser($user_id);
				//get hospital list
				$hospitals = $user->getHospitalList();
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
				$hospitals = null;
			}
		
			// remove the patient from the doctors list.
			$gender = $user->getGender();
			//echo $gender;
			$firstName = $user->getFirstname();
			$lastName = $user->getLastname();
			
			$address = explode('|', $user->getAddress());
			
			$contact = $user->getContact();			
			$username = $user->getUsername();
			$email = $user->getEmail();

			$dob = $user->getDoB();
			$year = date('Y', strtotime($user->getDoB()));
			$month = date('m', strtotime($user->getDoB()));
			$day = date('d', strtotime($user->getDoB()));
			
					
			//check to see if removing patient failed.
			if($username !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				$response["user"]["firstname"] = $firstName;
				$response["user"]["lastname"] = $lastName;
				$response["user"]["gender"] = ucwords($gender);
				$response["user"]["dob"] = $dob;
				$response["user"]["year"] = $year;
				$response["user"]["month"] = $month;
				$response["user"]["day"] = $day;
			
				$response["user"]["address1"] = $address[0];
				$response["user"]["address2"] = $address[1];
				$response["user"]["city"] = $address[2];
				$response["user"]["state"] = $address[3];
				$response["user"]["country"] = $address[4];
				$response["user"]["postal"] = $address[5];			
							
				$response["user"]["contact"] = $contact;
				$response["user"]["username"] = $username;
				$response["user"]["email"] = $email;			

				$response["hospitals"] = $hospitals;
				
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get Doctor profile";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "get_hospitals"){

		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
				$user = Doctor::createUser($user_id);
				$connectedHospitals = $user->getHospitalList();
				$response["connectedHospitals"] = $connectedHospitals;
			}
			
			// get list of all the hospitals 
			$hospitals = Hospital::getHospitalList();
			
			$doctors = null;
			for($i = 0; $i < sizeof($hospitals); $i++){
				$doctors[$i] = Hospital::getDoctorList($hospitals[$i]["hospital_id"]);
			}
			
			//check to see if removing patient failed.
			if($hospitals !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				$response["allHospitals"] = $hospitals;
				$response["doctors"] = $doctors;

				
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get Doctor profile";
				echo json_encode($response);	
			}
		}
	} else if($tag === "get_notifications"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		
		
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
				// Create Doctor user
				$user = Doctor::createUser($user_id);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
				
			$notification_list = $user->getNotificationList();
			if ($notification_list !== null) {
				foreach ($notification_list as $notification) {
					$notification_object = Notification::createNotification($notification['notification_id']);
					
					$response["notification_type"][] = Notification::findTypeName($notification_object->getTypeID());
					$response["notification_message"][] = $notification_object->__toString();
				}
				$response["success"] = 1;	
				echo json_encode($response);
			} else {
				//connected, but has no notifications.
				$response["success"] = 3;	
				echo json_encode($response);
			}
		}
	} else if($tag === "save_name"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$firstname = $_POST['firstname'];
		$lastname = $_POST['lastname'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.	
		
		if($session === $user_id){	
			// load user data from database
			$user = User::createUser($user_id);
			// set the firstname to that from POST
			$user->setFirstname($firstname);
			$user->setLastname($lastname);
			$success = $user->update();
			
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to update profile data";
				echo json_encode($response);	
			}
		}
	} else if($tag === "save_contact"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$contact = $_POST['contact'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.	
		
		if($session === $user_id){	
			// load user data from database
			$user = User::createUser($user_id);
			// set the contact to that from POST
			$user->setContact($contact);
			$success = $user->update();
			
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to update contact";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "save_address"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$address = $_POST['address'];	
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.		
		if($session === $user_id){	
			// load user data from database
			$user = User::createUser($user_id);
			// set the address to that from POST
			$user->setAddress($address);
			$success = $user->update();
			
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);			
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to update address";
				echo json_encode($response);	
			}
		}
	
	} else if($tag === "save_gender"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$gender = $_POST['gender'];
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.		
		if($session === $user_id){	
			// load user data from database
			$user = User::createUser($user_id);
			// set the firstname to that from POST
			$user->setGender($gender);
			$success = $user->update();
			
			// check if the function ran alright.
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);

				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to update profile data";
				echo json_encode($response);	
			}
		}
	} else if($tag === "save_dob"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$year = $_POST['year'];
		$month = $_POST['month'];
		$day = $_POST['day'];
		
		// Need to have the date in the right string format.
		$dob = $year."-".$month."-".$day;
		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		
		
		if($session === $user_id){	
			// load user data from database
			$user = User::createUser($user_id);
			// set the firstname to that from POST
			$user->setDoB($dob);
			$success = $user->update();
			
			// check if the function ran alright.
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to update profile data";
				echo json_encode($response);	
			}
		}
	} else if($tag === "register_push_notifications"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$reg = $_POST['regId'];
		$session = Session::findID($token);
		
		if($session === $user_id){	
			$user = User::createUser($user_id);
			$success = $user->attachAndroidID($reg);
		
			// check if the function ran alright.
			if($success){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);
			
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to register GCM ID to database";
				echo json_encode($response);	
			}
			
		} else {
			// No such function.
			$response["error"] = 1;
			$response["error_msg"] = "Failed to connect to GCM - invalid user";
			echo json_encode($response);
		}
		
	} else if($tag === "add_hospital"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$hospital_id = $_POST['hospital'];
		$session = Session::findID($token);
		
		if($session === $user_id){	
		
			if(User::findRole($user_id) === "doctor"){
				// Create Doctor user
				$user = Doctor::createUser($user_id);				
				$success = $user->attachToHospital($hospital_id);
		
				// check if the function ran alright.
				if($success){
					// session found and removed
					// echo json with success = 1
					$response["success"] = 1;	
					echo json_encode($response);
				
				} else {
					// user not found
					// echo json with error = 1
					$response["error"] = 1;
					$response["error_msg"] = "Failed to add hospital";
					echo json_encode($response);	
				}				
			} else {
				// invalid type of user
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "User is not a Doctor";
				echo json_encode($response);
			}					
		} else {
			// No such function.
			$response["error"] = 1;
			$response["error_msg"] = "Failed to connect to GCM - invalid user";
			echo json_encode($response);
		}

	} else if($tag === "remove_hospital"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];
		$hospital_id = $_POST['hospital'];

		$session = Session::findID($token);
		
		if($session === $user_id){	
		
			if(User::findRole($user_id) === "doctor"){
				// Create Doctor user
				$user = Doctor::createUser($user_id);				
				$success = $user->unattachFromHospital($hospital_id);
		
				// check if the function ran alright.
				if($success){
					// session found and removed
					// echo json with success = 1
					$response["success"] = 1;	
					echo json_encode($response);
				
				} else {
					// function failed
					// echo json with error = 1
					$response["error"] = 1;
					$response["error_msg"] = "Failed to remove hospital";
					echo json_encode($response);	
				}				
			} else {
				// invalid type of user
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "User is not a Doctor";
				echo json_encode($response);
			}					
		} else {
			// Session expired.
			$response["error"] = 1;
			$response["error_msg"] = "Failed: session expired";
			echo json_encode($response);
		}	

	} else if($tag === "get_symptoms"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$connection_id = $_POST['connectionID'];	
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){

				$doctorUser = Doctor::createUser($user_id);
				// check to see if the patient is connected to the doctor.
				if(!$doctorUser->isPatient($connection_id)){
					$response["error"] = 1;
					$response["error_msg"] = "Doctor not connected to patient";
					echo json_encode($response);
				}
				$user = Patient::createUser($connection_id);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
						
			$logList = $user->getSymptomList();		
			
			if($user !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				$response["symptoms"] = $logList;

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get log list";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "get_food"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$connection_id = $_POST['connectionID'];	
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){

				$doctorUser = Doctor::createUser($user_id);
				// check to see if the patient is connected to the doctor.
				if(!$doctorUser->isPatient($connection_id)){
					$response["error"] = 1;
					$response["error_msg"] = "Doctor not connected to patient";
					echo json_encode($response);
				}
				$user = Patient::createUser($connection_id);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}						
			$foodList = $user->getFoodList();		
			
			if($user !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				$response["foodList"] = $foodList;

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get log list";
				echo json_encode($response);	
			}
		}	
	}else if($tag === "delete_log"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
		$log_id = intval($_POST['logId']);	
		$type = $_POST['type'];		
				
		if($session === $user_id){	
			
			$removeLog = false;
			if($type === "logs"){			
				$dataLog = DataLog::createDataLog($log_id);

				if($dataLog !== null){
					if($dataLog->getUserID() === $user_id){
						$removeLog = $dataLog->remove();
					}
				}
			} else if($type === "food"){			
				$foodLog = Food::createFood($log_id);

				if($foodLog !== null){
					if($foodLog->getUserID() === $user_id){
						$removeLog = $foodLog->remove();
					}
				}
			} else if($type === "symptoms"){			
				$symptomLog = Symptom::createSymptom($log_id);

				if($symptomLog !== null){
					if($symptomLog->getUserID() === $user_id){
						$removeLog = $symptomLog->remove();
					}
				}
			}
			if($removeLog){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to delete datalog";
				echo json_encode($response);	
			}
		}	
	}  else if($tag === "get_logs_types"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){

				$response["error"] = 1;
				$response["error_msg"] = "Only Patient can access";
				echo json_encode($response);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
						
			$dataTypeList = DataLog::getDataLogTypeList();
			
			if($user !== null){
			
				// echo json with success = 1
				$response["success"] = 1;	
				$response["dataTypeList"] = $dataTypeList;

				echo json_encode($response);
								
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get log list";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "get_logs"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){

				$response["error"] = 1;
				$response["error_msg"] = "Only Patient can access";
				echo json_encode($response);
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
						
			$logList = $user->getDataLogList();		
			$dataTypeList = DataLog::getDataLogTypeList();
			
			if($user !== null){
			
				// echo json with success = 1
				$response["success"] = 1;	
				$response["logList"] = $logList;
				$response["dataTypeList"] = $dataTypeList;

				echo json_encode($response);
								
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get log list";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "get_patient_logs"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$patient_id = $_POST['patient_id'];		

		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
				// Create patient user.
				$patient = Patient::createUser($patient_id);
				
			} else {
				$response["error"] = 1;
				$response["error_msg"] = "Only Doctor can access";
				echo json_encode($response);
			}
						
			$logList = $patient->getDataLogList();		
			$dataTypeList = DataLog::getDataLogTypeList();
			
			if($logList !== null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				$response["logList"] = $logList;
				$response["dataTypeList"] = $dataTypeList;

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get log list";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "add_food"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$note = $_POST['notes']; 	
		$food = $_POST['food'];
		$calories = $_POST['calories'];
		
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}			
			// set as 0 as 0 means failure. If insert when okay, then anoter number will be assigned.
			$successFood = 0;
			$foodObject = new Food($user_id, $food, $calories, $note, null);
			$successFood = $foodObject->insert();
			
			
			if($successFood !== 0){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to add log";
				echo json_encode($response);	
			}
		}	
	}	else if($tag === "add_symptom"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$note = $_POST['notes']; 	
		$symptom_name = $_POST['symptoms'];
		$symptom_level = $_POST['severity'];
		
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}			
			// set as 0 as 0 means failure. If insert when okay, then anoter number will be assigned.
			$successSymptom = 0;
			$symptomObject = new Symptom($user_id, $symptom_name, $symptom_level, $note, $symptom_time = null);
			$successSymptom = $symptomObject->insert();
			
			
			if($successSymptom !== 0){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to add log";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "add_log"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$typeID = $_POST['type'];	
		$value = $_POST['value'];	
		$note = $_POST['notes']; 	
		
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
			
			$datalog_entry = preg_split('#(?<=\d)(?=[a-z])#i', preg_replace('/\s+/', '', $_POST['value']));
			$datalog_value = $datalog_entry[0];
			$datalog_unit = null;
			if (count($datalog_entry) === 2) {
				$datalog_unit = $datalog_entry[1];
			}
			
			$datalog = new Datalog($user_id, $typeID, $datalog_value, $datalog_unit, $note, null);			
			//insert into database and get return value
			$successLog = $datalog->insert();	
			
			if($successLog !== 0){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;	
				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to add log";
				echo json_encode($response);	
			}
		}	
	} else if($tag === "get_graph_data"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$graphType = $_POST['graphType'];	
		$compare = $_POST['compare'];	
		
		// check if we're logged in - check username assocciated with session token is the same as our username on app.
				
		if($session === $user_id){	
			
			if(User::findRole($user_id) === "doctor"){
			} else {
				// Create patient user.
				$user = Patient::createUser($user_id);
			}
			// get all the logs
			$logs = $user->getDataLogList($user_id);
			$specificLog = null;

			// go through all the log data and find the ones that match the type we're after.
			for($i = 0; $i < sizeof($logs); $i++){
				// get the name for the data type and then compare it.
				if(strcasecmp($graphType, Datalog::findTypeName($logs[$i]["datalog_type_id"])) === 0){
					$specificLog[] = $logs[$i]["datalog_value"];
				}
			}
					
			if($user !==null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;
				$response["logs"] = $specificLog;			

				echo json_encode($response);
				
			} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get specific log";
				echo json_encode($response);	
			}
		}	
	}else if($tag === "get_comparison"){
		
		// Get user info from database.
        $user_id = intval($_POST['userID']);
		$token = $_POST['session'];		
		$session = Session::findID($token);
		$datalog_type_id = $_POST['datalog_type_id'];
		$order = $_POST['order'];

	
		// check if we're logged in - check username assocciated with session token is the same as our username on app.			
		if($session === $user_id){	
			
			$comparison = Datalog::benchmark($user_id, $datalog_type_id);
					
			if($comparison !==null){
				// session found and removed
				// echo json with success = 1
				$response["success"] = 1;
				$response["comparison"] = $comparison;				
				echo json_encode($response);			
			} else {
				// user not found
				// echo json with error = 1
				$response["success"] = 3;
				$response["error_msg"] = "No data";
				echo json_encode($response);	
			}
		} else {
				// user not found
				// echo json with error = 1
				$response["error"] = 1;
				$response["error_msg"] = "Failed to get specific log";
				echo json_encode($response);	
			}			
	} else {
        // No such function.
		$response["error"] = 1;
		$response["error_msg"] = "No such function";
		echo json_encode($response);
    }
	
} else {
	//Access Denied
	$response["error"] = 1;
	$response["error_msg"] = "Access Denied";
	echo json_encode($response);
}
?>